<template>
  <div class="page-container">
    <!-- 导航栏 -->
    <van-nav-bar
      :title="word?.word || '单词详情'"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    >
      <template #right>
        <van-icon name="share" @click="shareWord" />
      </template>
    </van-nav-bar>

    <div v-if="word" class="word-detail">
      <!-- 单词卡片 -->
      <div class="word-card card">
        <div class="word-header">
          <h1 class="word-title">{{ word.word }}</h1>
          <div class="favorite-actions">
            <!-- 很陌生按钮 -->
            <van-button
              :class="['favorite-btn', { 'unfamiliar': getFavoriteLevel(word.id) === 1 }]"
              size="large"
              round
              @click="toggleFavorite(word.id, 1)"
            >
              <van-icon name="question" />
              <span>很陌生</span>
            </van-button>
            <!-- 有印象按钮 -->
            <van-button
              :class="['favorite-btn', { 'familiar': getFavoriteLevel(word.id) === 2 }]"
              size="large"
              round
              @click="toggleFavorite(word.id, 2)"
            >
              <van-icon name="like" />
              <span>有印象</span>
            </van-button>
          </div>
        </div>
        
        <div class="word-pronunciation">
          <van-icon name="volume-o" @click="playPronunciation" />
          <span>{{ word.pronunciation }}</span>
        </div>
      </div>

      <!-- 释义编辑 -->
      <div class="meaning-section card">
        <div class="section-header">
          <h3>释义</h3>
          <van-button
            v-if="!isEditing"
            type="primary"
            size="small"
            @click="startEdit"
          >
            编辑
          </van-button>
          <div v-else class="edit-actions">
            <van-button size="small" @click="cancelEdit">取消</van-button>
            <van-button type="primary" size="small" @click="saveMeaning">保存</van-button>
          </div>
        </div>
        
        <div v-if="!isEditing" class="meaning-display">
          <p>{{ word.meaning }}</p>
        </div>
        
        <div v-else class="meaning-edit">
          <van-field
            v-model="editingMeaning"
            type="textarea"
            placeholder="请输入单词释义"
            rows="3"
            autosize
          />
        </div>
      </div>

      <!-- 例句 -->
      <div class="example-section card">
        <h3>例句</h3>
        <div class="example-item">
          <p class="example-text">{{ word.example }}</p>
          <p class="example-translation">{{ word.translation }}</p>
        </div>
      </div>

      <!-- 学习记录 -->
      <div class="record-section card">
        <h3>学习记录</h3>
        <div class="record-stats">
          <div class="record-item">
            <span class="record-label">收藏状态:</span>
            <span class="record-value">
              <van-tag v-if="getFavoriteLevel(word.id) === 1" type="warning">很陌生</van-tag>
              <van-tag v-else-if="getFavoriteLevel(word.id) === 2" type="success">有印象</van-tag>
              <van-tag v-else type="default">未收藏</van-tag>
            </span>
          </div>
          <div class="record-item">
            <span class="record-label">查看次数:</span>
            <span class="record-value">{{ viewCount }}</span>
          </div>
          <div class="record-item">
            <span class="record-label">最后查看:</span>
            <span class="record-value">{{ lastViewTime }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <van-loading size="24px">加载中...</van-loading>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useWordStore } from '@/stores/word'
import { showToast, showConfirmDialog } from 'vant'

export default {
  name: 'WordDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const wordStore = useWordStore()
    
    const isEditing = ref(false)
    const editingMeaning = ref('')
    const viewCount = ref(1)
    const lastViewTime = ref(new Date().toLocaleString())

    // 计算属性
    const word = computed(() => {
      return wordStore.getWordById(route.params.id)
    })

    // 方法
    const goBack = () => {
      router.back()
    }

    const shareWord = async () => {
      if (navigator.share) {
        try {
          await navigator.share({
            title: `单词: ${word.value.word}`,
            text: `${word.value.word} ${word.value.pronunciation}\n${word.value.meaning}`,
            url: window.location.href
          })
        } catch (error) {
          console.log('分享失败:', error)
        }
      } else {
        // 复制到剪贴板
        const text = `${word.value.word} ${word.value.pronunciation}\n${word.value.meaning}`
        navigator.clipboard.writeText(text).then(() => {
          showToast('已复制到剪贴板')
        })
      }
    }

    const playPronunciation = () => {
      // 模拟发音功能
      showToast('播放发音')
      // 实际项目中可以集成语音合成API
    }

    const startEdit = () => {
      isEditing.value = true
      editingMeaning.value = word.value.meaning
    }

    const cancelEdit = () => {
      isEditing.value = false
      editingMeaning.value = ''
    }

    const saveMeaning = async () => {
      if (!editingMeaning.value.trim()) {
        showToast('释义不能为空')
        return
      }
      
      try {
        wordStore.updateWordMeaning(word.value.id, editingMeaning.value)
        isEditing.value = false
        showToast('保存成功')
      } catch (error) {
        showToast('保存失败')
      }
    }

    const toggleFavorite = (wordId, level) => {
      wordStore.toggleFavorite(wordId, level)
      const currentLevel = wordStore.getFavoriteLevel(wordId)
      if (currentLevel === level) {
        const levelText = level === 1 ? '很陌生' : '有印象'
        showToast(`已标记为${levelText}`)
      } else if (currentLevel === 0) {
        showToast('已取消收藏')
      } else {
        const levelText = currentLevel === 1 ? '很陌生' : '有印象'
        showToast(`已更改为${levelText}`)
      }
    }

    const getFavoriteLevel = (wordId) => {
      return wordStore.getFavoriteLevel(wordId)
    }

    // 生命周期
    onMounted(() => {
      if (!word.value) {
        showToast('单词不存在')
        router.back()
      } else {
        // 增加查看次数
        viewCount.value++
        lastViewTime.value = new Date().toLocaleString()
      }
    })

    return {
      word,
      isEditing,
      editingMeaning,
      viewCount,
      lastViewTime,
      goBack,
      shareWord,
      playPronunciation,
      startEdit,
      cancelEdit,
      saveMeaning,
      toggleFavorite,
      getFavoriteLevel
    }
  }
}
</script>

<style scoped>
.word-detail {
  padding: 0 12px 12px;
}

.word-card {
  margin-bottom: 16px;
  padding: 20px;
}

.word-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.word-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-color);
  margin: 0;
}

.favorite-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.favorite-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  background: white;
  color: var(--text-color-3);
  transition: all 0.3s;
  min-width: 80px;
}

.favorite-btn.unfamiliar {
  background: var(--warning-color);
  border-color: var(--warning-color);
  color: white;
}

.favorite-btn.familiar {
  background: var(--success-color);
  border-color: var(--success-color);
  color: white;
}

.word-pronunciation {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: var(--text-color-2);
  font-style: italic;
}

.word-pronunciation .van-icon {
  cursor: pointer;
  color: var(--primary-color);
}

.meaning-section,
.example-section,
.record-section {
  margin-bottom: 16px;
  padding: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--text-color);
}

.edit-actions {
  display: flex;
  gap: 8px;
}

.meaning-display p {
  margin: 0;
  font-size: 16px;
  line-height: 1.6;
  color: var(--text-color);
}

.example-item {
  border-left: 3px solid var(--primary-color);
  padding-left: 12px;
}

.example-text {
  font-size: 16px;
  color: var(--text-color);
  margin-bottom: 8px;
  font-style: italic;
}

.example-translation {
  font-size: 14px;
  color: var(--text-color-2);
  margin: 0;
}

.record-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-label {
  font-size: 14px;
  color: var(--text-color-2);
}

.record-value {
  font-size: 14px;
  color: var(--text-color);
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>